<template>
  <div v-loading="loading" class="index-container">
    <div class="welcome-info">
      <div class="avatar-container">
        <Avatar icon="ios-person" style="margin-left: 20px"/>
      </div>
      <div class="world">
        <p style="margin-bottom: 20px">
          <span>Hi，{{ $utils.getUserInfo().realName }}</span>
          <span v-if="!isCurrentAgentPermission">
                        {{ `(${$utils.getUserInfo().entrustingPartyName})` }}
                    </span>
          <span>，欢迎使用大迈冷链智慧管理平台！</span>
        </p>
        <p>冷链平台可视化，全方位掌控采购和履行订单直到最终交付。</p>
      </div>
      <div v-if="isCurrentAgentPermission" class="select-wrap">
        <div class="select-wrap__content">
          <label>货主/结算客户</label>
          <el-select
              v-model="selectCustomerIds"
              multiple
              filterable
              collapse-tags
              size="mini"
              style="width: 300px"
              @visible-change="onChangeCustomer"
          >
            <el-option
                v-for="item in $utils.getUserInfo().customerInfoList || []"
                :key="item.customerPartyID"
                :value="item.customerPartyCode"
                :label="item.customerPartyName"
            />
          </el-select>
        </div>
      </div>
      <el-dialog
          :visible.sync="dialogVisible"
          width="40%"
          :close-on-press-escape="false"
          :close-on-click-modal="false">
        <hr style="background-color: #ddd;margin-top:10px;margin-bottom:10px;height: 1px;border: 0px;"/>
        <template #title>
          <div style="font-size: 16px;color: #444;font-weight: 700;">货物失效预警</div>
        </template>
        <div style="height:400px;overflow:auto">
          <div v-for="(item, index) in notices" :key="index" style="color:#444;position:relative;margin-top:10px;">
            <div v-if="itemS.matName.length <= 4" v-for="(itemS, indexS) in item" :key="indexS"
                 style="height:60px;line-height:60px;width:82%">
              <div style="display: inline-block">
                {{ (itemS.totalWeight / 1000).toFixed(3) + '吨' + '(' + itemS.caseNum + ('柜') + ')' }}
              </div>
              <div style="display:inline-block;font-weight: 700;color:blue"> {{ itemS.matName }}</div>
              <div v-if="((itemS.dateExpire - itemS.platformPushDate) > 0)" style="display:inline-block;">{{ '将于' }}
              </div>
              <div style="display:inline-block;font-weight:700;color:blue"> {{
                  ((itemS.dateExpire - itemS.platformPushDate) > 0 ? Math.trunc((((itemS.dateExpire - itemS.platformPushDate) / 86400000))) : '已失效')
                }}
              </div>
              <div v-if="(itemS.dateExpire - itemS.platformPushDate) > 0" style="display:inline-block;">{{
                  '天后失效'
                }}
              </div>
              <div style="display:inline-block;"> {{ '，失效日期：' }}</div>
              <div style="display:inline-block;font-weight:700;color:blue"> {{
                  $utils.timestampToDate(itemS.dateExpire)
                }}
              </div>
              <div style="display:inline-block">{{ '，请及时处理' }}</div>
            </div>
            <div v-if="itemS.matName.length > 4" v-for="(itemS, indexS) in item" :key="indexS"
                 style="height:60px;line-height:30px;width:82%">
              <div style="display: inline-block">
                {{ (itemS.totalWeight / 1000).toFixed(3) + '吨' + '(' + itemS.caseNum + ('柜') + ')' }}
              </div>
              <div style="display:inline-block;font-weight: 700;color:blue"> {{ itemS.matName }}</div>
              <div v-if="(itemS.dateExpire - itemS.platformPushDate) > 0" style="display:inline-block;">{{ '将于' }}
              </div>
              <div style="display:inline-block;font-weight:700;color:blue"> {{
                  ((itemS.dateExpire - itemS.platformPushDate) > 0 ? Math.trunc((((itemS.dateExpire - itemS.platformPushDate) / 86400000))) : '已失效')
                }}
              </div>
              <div v-if="(itemS.dateExpire - itemS.platformPushDate) > 0" style="display:inline-block;">{{
                  '天后失效，'
                }}
              </div>
              <div style="display:inline-block;"> {{ '，失效日期：' }}</div>
              <div style="display:inline-block;font-weight:700;color:blue"> {{
                  $utils.timestampToDate(itemS.dateExpire)
                }}
              </div>
              <div style="display:inline-block">{{ '，请及时处理' }}</div>
            </div>
            <el-button style="float:right;position:absolute;top:40%;right:2%;z-index:1000;height: 30px;width:80px"
                       size="mini" type="primary" @click="lookInfo(item[0])"> 查看详情
            </el-button>
            <hr style="background-color: #ddd;margin-top:10px;margin-bottom:10px;height: 1px;border: 0px;"/>
          </div>
        </div>
        <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">关闭</el-button>
                    </span>
        </template>
      </el-dialog>
    </div>
    <div class="work-frame">
      <div class="work-left-container">
        <Card v-loading="dataLoading">
          <p style="font-weight: 700;font-size:16px;position: relative">
            数据汇总
            <DatePicker v-model="dataSummaryYear" class="weizhi" type="year" style="width: 100px;"
                        @on-change="dataSummaryYearChange"/>
          </p>
          <div class="card-item">
            <Row type="flex" align="middle" style="height: 100%;">
              <i-col span="6" style="border-right: 1px solid rgba(0, 0, 0, .45);margin-left:7%">
                <p style="font-size: 14px; color:rgba(0, 0, 0, 0.45);">库存<a
                  style="font-size:13px;color:blue;font-weight:300;float:right;margin-right:10px"
                  @click="$router.push({path: '/warehousingService/inventory-info'})">查看详情<i
                  class="el-icon-arrow-right"></i></a></p>
                <p style="font-size: 20px; font-weight: 700; position: relative;margin-top: 20px">
                  {{ inventoryInfo.stockWeight ? inventoryInfo.stockWeight : 0 }}吨
                </p>
                <p style="font-size: 14px; color:rgba(0, 0, 0, 0.85);margin-top: 40px">{{
                    inventoryInfo.stockTotal ? inventoryInfo.stockTotal : 0
                  }}件/{{ inventoryInfo.stockTraceNum ? inventoryInfo.stockTraceNum : 0 }}托</p>
              </i-col>
              <i-col span="6" style="margin-left:7%">
                <p style="font-size: 14px; color:rgba(0, 0, 0, 0.45);">总入库</p>
                <p style="font-size: 20px; font-weight: 700;margin-top: 20px">
                  {{ outInBoundData.intoWeightSum ? (outInBoundData.intoWeightSum / 1000).toFixed(3) : 0 }}吨</p>
                <p style="font-size: 14px; color:rgba(0, 0, 0, 0.85);margin-top: 40px">{{
                    outInBoundData.intoTotalSum ? outInBoundData.intoTotalSum : 0
                  }}件/{{ outInBoundData.intoTraceSum ? outInBoundData.intoTraceSum : 0 }}托</p>
              </i-col>
              <i-col span="6" style="margin-left:7%">
                <p style="font-size: 14px; color:rgba(0, 0, 0, 0.45);">总出库</p>
                <p style="font-size: 20px; font-weight: 700;margin-top: 20px">
                  {{ outInBoundData.outWeightSum ? (outInBoundData.outWeightSum / 1000).toFixed(3) : 0 }}吨</p>
                <p style="font-size: 14px; color:rgba(0, 0, 0, 0.85);margin-top: 40px">{{
                    outInBoundData.outTotalSum ? outInBoundData.outTotalSum : 0
                  }}件/{{ outInBoundData.outTraceSum ? outInBoundData.outTraceSum : 0 }}托</p>
              </i-col>
            </Row>
          </div>
        </Card>
        <Card style="margin-top: 10px">
          <p style="font-weight: 700;font-size:16px;">今日作业</p>
          <el-row style="height: 330px;" :gutter="5">
            <el-col :span="24">
              <div class="card-item" v-loading="dataLoading">
                <el-row>
                  <el-col :span="24">
                    <el-row style="height: 100%;">
                      <el-col :span="24">
                        <div style="height: 100%;display: flex;flex-direction: column;justify-content: space-around">
                          <div style="display: flex;">
                            <div style="width: 50%">
                              <p style="margin-bottom: 5px">
                                入库箱数
                                <span style="font-weight: bold; margin-left: 40px; font-size: 16px">
                                  {{ summaryData.intoBoxSum !== undefined && summaryData.totalIntoBoxSum !== undefined ? `${summaryData.intoBoxSum}柜/${summaryData.totalIntoBoxSum}柜` : '' }} <span style="font-weight: normal;">(计划量)</span>
                                </span>
                              </p>
                            </div>
                            <div style="width: 50%;">
                              <p style="margin-bottom: 5px;">已入库件数
                                <span style="font-weight: bold; margin-left: 40px; font-size: 16px">
                                  {{ summaryData.intoQtySum ? summaryData.intoQtySum : 0 }} 件
                                </span>
                              </p>
                            </div>
                          </div>
                          <div style="display: flex;margin-top: 30px">
                            <div style="width: 50%">
                              <p style="margin-bottom: 5px">已入库吨数
                                <span style="font-weight: bold; margin-left: 40px; font-size: 16px">
                                  {{ summaryData.intoTonSum ? Number(summaryData.intoTonSum).toFixed(3) : 0 }} 吨
                                </span>
                              </p>
                            </div>
                            <div style="width: 50%;">
                              <p style="margin-bottom: 5px;">已入库托数
                                <span style="font-weight: bold; margin-left: 40px; font-size: 16px">
                                  {{ summaryData.intoTraceSum ? summaryData.intoTraceSum : 0 }} 托
                                </span>
                              </p>
                            </div>
                          </div>
                        </div>
                      </el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="24">
                    <hr style="margin: 50px 0"/>
                    <el-row>
                      <el-col :span="24">
                        <div style="display: flex;flex-direction: column;justify-content: space-around">
                          <div style="display: flex;">
                            <div style="width: 50%">
                              <p style="margin-bottom: 5px">
                                出库车数
                                <span style="font-weight: bold; margin-left: 40px; font-size: 16px">
                                  {{ summaryData.outTruckSum !== undefined && summaryData.totalOutTruckSum !== undefined ? `${summaryData.outTruckSum}车/${summaryData.totalOutTruckSum}车` : '' }} <span style="font-weight: normal;">(计划量)</span>
                                </span>
                              </p>
                            </div>
                            <div style="width: 50%;">
                              <p style="margin-bottom: 5px;">已出库件数
                                <span style="font-weight: bold; margin-left: 40px; font-size: 16px">
                                  {{ summaryData.outQtySum ? summaryData.outQtySum : 0 }} 件
                                </span>
                              </p>
                            </div>
                          </div>
                          <div style="display: flex; margin-top: 30px">
                            <div style="width: 50%">
                              <p style="margin-bottom: 5px">已出库吨数
                                <span style="font-weight: bold; margin-left: 40px; font-size: 16px">
                                  {{ summaryData.outTonSum ? Number(summaryData.outTonSum).toFixed(3) : 0 }} 吨
                                </span>
                              </p>
                            </div>
                            <div style="width: 50%;">
                              <p style="margin-bottom: 5px;">已出库托数
                                <span style="font-weight: bold; margin-left: 40px; font-size: 16px">
                                  {{ summaryData.outTraceSum ? summaryData.outTraceSum : 0 }} 托
                                </span>
                              </p>
                            </div>
                          </div>
                        </div>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
        </Card>
      </div>
      <div class="work-right-container">
        <Card>
          <div style="font-weight: 700;font-size:16px">品类分析</div>
          <mat-type-top-five ref="matTypeTopFiveDom" />
        </Card>
        <Card style="margin-top: 10px">
          <div style="display: flex; justify-content: space-between">
            <div style="font-weight: 700;font-size:16px; ">WMS任务统计</div>
            <el-date-picker
              key="date-picker-day"
              v-model="dates"
              style="width: 400px"
              size="mini"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="wmsTaskStaticis"
            >
            </el-date-picker>
          </div>
          <wms-task-line ref="wmsTaskLineDom" />
        </Card>
      </div>
    </div>
  </div>
</template>

<script>
import indexStaticApi from '@/api/indexStatic.js';
import {
  getAllWareList,
  getAllWareDataList,
  selectToadySummary,
  outInBoundStatusV2Toc,
  clientgetPushByUser,
  doneMessage
} from '@/api/warehouse/home.js';
import ProgressBar from '@/view/component/progress-bar/index.vue';
import * as echarts from 'echarts';
import {on, off} from '@/libs/tools'
import moment from 'moment';
import {getCurrentAgentPermissionWareHouse} from '@/libs/handleWareHouseList';
import {useHttp} from "@/view/wms/js";
import MatTypeTopFive from "@/view/home/chart/MatTypeTopFive.vue";
import WmsTaskLine from "@/view/home/chart/WmsTaskLine.vue";

export default {
  name: 'WorkbenchIndex',
  components: {
    WmsTaskLine,
    MatTypeTopFive,
    ProgressBar
  },
  computed: {
    isCurrentAgentPermission() {
      // return true;
      return !!this.$utils.getUserInfo().currentAgentPermission;
    }
  },
  data() {
    return {
      dates: '',
      loading: false,
      selectCustomerIds: [],
      summaryData: {},
      notices: [],
      dialogVisible: false,
      dataLoading: false,
      outInBoundData: {},
      inventoryInfo: {},
      whCodeList: [],
      whCodes: [],
      ccisWhIds: [],
      wareList: [],
      wmsUrl: '',
      haveInHandData: {},
      businessInfo: {},
      shipInfo: {},
      businessInfoDom: null,
      logisticsDom: null,
      dataSummaryYear: new Date(new Date().getFullYear(), 0, 1),
      commerceMonth: new Date(),
      commerceMonth1: [],
      logisticsMonth: new Date(),
      logisticsMonth1: []
    };
  },
  methods: {
    async getWareHouseData() {
      const response = await getAllWareDataList(this.ccisWhIds);
      if (response.data.returnCode === 200) {
        this.whCodeList = [];
        response.data.returnData.forEach(x => {
          x.returnData.forEach(item => {
            item.whId = x.whId
          });
          this.whCodeList = this.whCodeList.concat(x.returnData);
        });
      } else {
        this.$Message.error(response.data.returnMsg);
      }
    },
    async initToadySummary() {
      let body = [];
      this.ccisWhIds.forEach(x => {
        let whCodes = this.whCodeList.filter(item => item.whId == x);
        if (whCodes && whCodes.length > 0) {
          body.push({
            whId: x,
            ownerCodeList: this.selectCustomerIds
          });
        }
      });
      this.dataLoading = true;
      const response = await useHttp('/api/wms_stock/selectToadySummary', {
        whCodeList: this.wareList.map(item => item.whCode),
        ownerCodeList: this.selectCustomerIds
      }, this.wmsUrl);
      // await selectToadySummary(body);
      if (response.data.returnCode === 200) {
        this.inventoryInfo = response.data.returnData;
        this.summaryData = response.data.returnData;
      } else {
        this.$Message.error(response.data.returnMsg);
      }
      this.dataLoading = false;
    },
    async initInOutSummary() {
      const d = new Date(new Date().getTime() - 6 * 30 * 24 * 3600 * 1000);
      let body = this.ccisWhIds.map(x => {
        return {
          whId: x,
          whCodes: this.whCodeList.filter(item => item.whId == x).map(x => x.whCode),
          dateField: 'month',
          // startTime: 1577808000000,
          // endTime: this.handleDate(new Date()),
          ownerCodeList: this.selectCustomerIds,
          startYear: new Date(moment(this.dataSummaryYear).format('YYYY-MM-DD')),
          endYear: new Date(moment(this.dataSummaryYear).format('YYYY-MM-DD'))
        };
      });
      const response = await outInBoundStatusV2Toc(body);
      if (response.data.returnCode === 200) {
        let returnData = response.data.returnData;
        this.outInBoundData = returnData;
      } else {
        this.$Message.error(response.data.returnMsg);
      }
    },

    getclientgetPushByUser() {
      setTimeout(() => {
        clientgetPushByUser(this.selectCustomerIds).then(response => {
          if (response.data.returnCode === 200) {
            this.notices = response.data.returnData;
            this.dialogVisible = true;
          }
        })
      }, 1000);
    },

    async initData() {
      const {data, message, error} = await getCurrentAgentPermissionWareHouse();
      if (data) {
        this.wareList = data;
        this.wmsUrl = this.wareList[0].ipProt;
        this.ccisWhIds = this.wareList.map(x => x.id);
      } else if (message) {
        this.$Message.error(message);
      }
      this.whCodes = this.wareList.map(item => item.whCode);
      await this.getWareHouseData();
      this.initToadySummary();
      this.initInOutSummary();
      this.$nextTick(() => {
        this.$refs.matTypeTopFiveDom.init(this.wmsUrl, this.whCodes, this.selectCustomerIds);
      });
      this.wmsTaskStaticis();
    },
    wmsTaskStaticis() {
      if (!this.dates || (Array.isArray(this.dates) && !this.dates.length)) {
        return this.$message.warning('请选择日期！');
      }
      this.$nextTick(() => {
        this.$refs.wmsTaskLineDom.init(this.wmsUrl, this.whCodes, this.selectCustomerIds, this.dates);
      });
    },
    dataSummaryYearChange() {
      this.initInOutSummary();
    },

    lookInfo(row) {
      this.$router.push({
        name: 'inventoryInfo',
        params: {
          matName: row.matName,
          dateExpire: row.dateExpire
        }
      });
      doneMessage(row.id).then(response => {
        if (response.data.returnCode == 200) {
          this.getPlatformPageMessage();
        } else {
          proxy.$util.message(response.returnMsg, 'error');
        }
      });
      this.dialogVisible = false;
      this.dialogVisible = false;
    },

    async onChangeCustomer(val) {
      if (val) return;
      this.loading = true;
      Promise.all([this.initToadySummary(), this.initInOutSummary()]).finally(() => (this.loading = false));
    }
  },
  mounted() {
    let curDate = new Date();
    let preDate = new Date(curDate.getTime() - 24*60*60*1000); //前一天
    this.dates = [new Date(new Date().getFullYear(), new Date().getMonth(), 1), new Date(preDate)]
  },
  watch: {
    '$store.state.user.userInfo': {
      handler(value) {
        if (!value || !value.entrustingPartyCode) return;
        this.selectCustomerIds = [this.$utils.getUserInfo().entrustingPartyCode];
        this.initData();
        setTimeout(() => {
          this.getclientgetPushByUser();
        }, 1000);
      },
      deep: true,
      immediate: true
    }
  }
};
</script>
<style lang="less">
.el-dialog__body {
  padding: 0px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}

.index-container {
  .ivu-card-body {
    height: 100% !important;
  }
}
</style>
<style scoped lang="less">
@import "workbench";
.weizhi {
  position: absolute;
  right: 10px;
}

.index-container {
  background-color: #f0f3f7;
  padding: 20px;
  width: 100%;

  .avatar-container {
    height: 100%;
    width: 50px;
    display: flex;
    align-items: center;
  }

  .welcome-info {
    width: 100%;
    height: 15vh;
    background: url("../../assets/images/index/index-bg.png");
    background-size: cover;
    display: flex;
    justify-content: start;
    align-items: center;
    padding-left: 5%;
  }

  .world {
    color: #ffffff;
    font-size: 14px;
    padding-left: 30px;
  }
}

.go-card {
  position: absolute;
  margin-left: 20px;
  margin-top: 3px;
  height: 16px;
  width: 16px;
  line-height: 16px;
  text-align: center;
  border: 1px solid;
  border-radius: 50%;
  font-size: 12px;
  cursor: pointer;
}

.statistical-data-container {
  padding: 0 10%;
  display: flex;
  justify-content: space-around;
  margin-top: 50px;

  .title {
    font-size: 14px;
    font-weight: 700;
  }

  .number {
    font-size: 30px;
    font-weight: 700;
    color: rgba(0, 0, 0, 0.85);

    span {
      font-size: 12px;
      color: rgba(0, 0, 0, 0.45);
      overflow-wrap: break-word;
      margin-left: 10px;
    }

    .right-arrow, .lineChart {
      margin-left: 20px;
      cursor: pointer;

      &:hover {
        opacity: .7;
      }
    }
  }

  .describe {
    overflow-wrap: break-word;
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
    white-space: nowrap;

    span {
      overflow-wrap: break-word;
      color: rgba(0, 0, 0, 0.85);
      font-size: 12px;
      white-space: nowrap;
      margin-left: 10px;
      font-weight: 700;
    }
  }
}

.card-item {
  position: relative;
  width: 100%;
  // box-shadow: 0px 0px 16px 0px rgba(27, 46, 137, 0.15);
  height: 100%;
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-top: 10px;
}

.index-foot {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .customer-service {
    .title {
      font-weight: 700;
      margin-bottom: 30px;
    }

    .phone {
      font-weight: 700;
      margin-bottom: 30px;
      display: flex;
      align-items: center;

      span {
        margin-left: 10px;
      }
    }

    .service-btn {
      background-color: rgba(79, 104, 232, 1);

      &:hover {
        opacity: .8;
      }
    }

    .feedback-btn {
      color: rgba(79, 104, 232, 1);
      border: 1px solid rgba(79, 104, 232, 1);
      margin-left: 10px;

      &:hover {
        opacity: .8;
      }
    }
  }

  .applet {
    display: flex;
    align-items: center;

    p {
      padding: 5px 10px;
    }

    p:first-child {
      overflow-wrap: break-word;
      color: rgba(0, 0, 0, 0.85);
      font-size: 14px;
      white-space: nowrap;
      font-weight: 700;
    }

    p:last-child {
      overflow-wrap: break-word;
      color: rgba(0, 0, 0, 0.65);
      font-size: 12px;
      white-space: nowrap;
      font-weight: 700;
    }
  }

  .related-links {
    display: flex;
    justify-content: space-around;

    .img-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 60px;
      border-radius: 10px;
      border: 1px solid rgba(217, 217, 217, 1);
      width: 60px;
      padding: 4px;
      margin-left: 20px;

      img {
        width: 80%;
        height: 80%;
      }
    }
  }
}

.select-wrap {
  flex: 1;
  padding-right: 36px;
  text-align: right;
  height: 50px;

  label {
    color: #fff;
    margin-right: 8px;
  }
}
</style>
